import json
import random
from datetime import datetime
from urllib.parse import quote

import requests
from flask import Flask, jsonify, request
from loguru import logger
from sqlalchemy import create_engine, Column, Integer, String, insert, DateTime
from sqlalchemy.orm import declarative_base, sessionmaker

logger.add("logs/unopened_sql.log", rotation="1 MB")
password = "Wangyu@915398"
encoded_password = quote(password)
DATABASE_URI = f"mysql+pymysql://root:{encoded_password}@8.155.30.52:3306/lottery2"
engine = create_engine(DATABASE_URI, pool_size=10, max_overflow=20, pool_timeout=30)
Session = sessionmaker(bind=engine)
Base = declarative_base()
import threading
import time

import kdl
from loguru import logger


class ProxyPool:
    def __init__(self, username, password, areas=('北京', '上海', '广东')):
        self.auth = kdl.Auth("oq2ahc8pw3vftx8bmcvl", "00jx1mm7gynm3t9j2hehtbhy8n70c304")
        self.client = kdl.Client(self.auth)
        self.username = username
        self.password = password
        self.areas = areas
        self.current_ip = []
        self.expiry_time = 0
        self.lock = threading.Lock()
        self._stop_event = threading.Event()

    def _update_proxy(self):
        try:
            new_ips = self.client.get_dps(
                num=1,
                sign_type='hmacsha1',
                format='json',
                pt=1,
                area=','.join(self.areas)
            )
            if new_ips and len(new_ips) > 0:
                new_ip = new_ips[0]
                expiry_info = self.client.get_dps_valid_time(
                    new_ip,
                    sign_type='hmacsha1'
                )
                self.current_ip.append(new_ip)
                self.expiry_time = int(expiry_info.get(new_ip, 0))
                logger.info(f"🟢更新代理: {new_ip} (剩余时间： {self.expiry_time}s)")
        except Exception as e:
            logger.info(f"🔴 Error updating proxy: {e}")

    def _check_loop(self):
        while not self._stop_event.is_set():
            time.sleep(self.expiry_time / 3)
            try:
                with self.lock:
                    if self.expiry_time > 0:

                        expiry_info = self.client.get_dps_valid_time(
                            self.current_ip[-1],
                            sign_type='hmacsha1'
                        )
                        remaining = int(expiry_info.get(self.current_ip[-1], 0))
                        if remaining <= 76:
                            logger.info(f"代理 {self.current_ip[-1]} 剩余时间 ({remaining}s), 去更新中...")
                            self._update_proxy()
                        else:
                            self.expiry_time = remaining
                logger.info(f"🧰 代理 {self.current_ip[-1]} 剩余时间 ({self.expiry_time}s)")
            except Exception as e:
                if self.expiry_time <= 100:
                    self._update_proxy()
                    logger.info(f"🔴检查代理失败: {e}, 时间不足100s，去更新中...")
                else:
                    self.expiry_time -= self.expiry_time / 3
                    logger.info(f"🔴检查代理失败: {e}, 还剩下{self.expiry_time}s")

    def get_proxies(self):
        with self.lock:
            if not self.current_ip:
                raise ValueError("🔴 没有可用代理")

            return {
                "http": f"http://{self.username}:{self.password}@{self.current_ip[-1]}/",
                "https": f"http://{self.username}:{self.password}@{self.current_ip[-1]}/"
            }

    def stop(self):
        self._stop_event.set()
        self.check_thread.join()

    @property
    def stop_event(self):
        return self._stop_event

    def get_fresh_proxy(self):
        with self.lock:
            if self.current_ip:
                expiry_info = self.client.get_dps_valid_time(
                    self.current_ip[-1],
                    sign_type='hmacsha1'
                )
                remaining = int(expiry_info.get(self.current_ip[-1], 0))
                if remaining > 30:
                    return {
                        "http": f"http://{self.username}:{self.password}@{self.current_ip[-1]}/",
                        "https": f"http://{self.username}:{self.password}@{self.current_ip[-1]}/"
                    }
            logger.info("🔄 代理已过期，正在获取新代理...")
            self._update_proxy()
            time.sleep(1)


pool = ProxyPool(
    username="d2002701022",
    password="b7zf0dk9",
    areas=('北京', '上海', '广东')
)


def insert_data(data, max_retries=3):
    retries = 0
    while retries < max_retries:
        session = Session()
        try:

            session.bulk_save_objects(data)
            session.commit()
            logger.info("数据插入成功。")
            return
        except SQLAlchemyError as e:

            session.rollback()
            retries += 1
            logger.info(f"第 {retries} 次尝试插入数据失败: {e}")
        finally:

            session.close()

    logger.info("数据插入失败，已达到最大重试次数。")
    raise Exception("插入数据失败，重试次数已耗尽。")


class UnopenedHad(Base):
    __tablename__ = 'unopened_had'

    id = Column(Integer, primary_key=True, autoincrement=True)
    match_id = Column(String(32))
    winning_odds = Column(String(12))
    flat_odds = Column(String(12))
    negative_odds = Column(String(12))
    time = Column(DateTime)


class UnopenedHHad(Base):
    __tablename__ = 'unopened_hhad'

    id = Column(Integer, primary_key=True, autoincrement=True)
    match_id = Column(String(32))
    winning_odds = Column(String(12))
    flat_odds = Column(String(12))
    negative_odds = Column(String(12))
    time = Column(DateTime)


class UnopenedLottery(Base):
    __tablename__ = 'unopened_lottery'
    match_id = Column(Integer, primary_key=True, comment='比赛id')
    match_time = Column(DateTime, nullable=True, comment='比赛时间')
    host_name = Column(String(255), nullable=True, comment='主队名称')
    guest_name = Column(String(255), nullable=True, comment='客队名称')
    internation_attribute = Column(String(255), nullable=True, comment='国际类型')
    match_number = Column(String(255), nullable=True, comment='比赛编号')


def insert_unopenedLottery_data(data, max_retries=3):
    retries = 0
    while retries < max_retries:
        session = Session()
        try:

            for day in data:

                match_date = day["比赛日期"]
                match_time = day["比赛时间"]
                match_datetime_str = f"{match_date} {match_time}"
                match_datetime = datetime.strptime(match_datetime_str, '%Y-%m-%d %H:%M:%S')
                exists = session.query(
                    session.query(UnopenedLottery).filter(
                        UnopenedLottery.match_id == day['比赛id'],
                        UnopenedLottery.host_name == day["主队简称"],
                        UnopenedLottery.guest_name == day["客队简称"],
                        UnopenedLottery.internation_attribute == day["联赛简称"]
                    ).exists()
                ).scalar()
                if exists:
                    continue

                entry = UnopenedLottery(
                    match_id=day["比赛id"],
                    match_time=match_datetime,
                    host_name=day["主队简称"],
                    guest_name=day["客队简称"],
                    internation_attribute=day["联赛简称"],
                    match_number=day["比赛编号"]
                )

                session.add(entry)

                session.commit()
                logger.info(f"{day['比赛id']}数据插入成功！")
            return
        except SQLAlchemyError as e:
            session.rollback()
            retries += 1
            logger.info(f"第 {retries} 次尝试插入数据失败: {e}")
        finally:
            session.close()

    logger.info("数据插入失败，已达到最大重试次数。")
    raise Exception("插入数据失败，重试次数已耗尽。")


def insert_胜平负(odds_list):
    session = Session()
    try:
        matched_records = session.query(UnopenedHad).filter(UnopenedHad.match_id == odds_list[0]['id']).all()
        if len(odds_list) == len(matched_records):
            return
        for odds_info in odds_list:
            exists = session.query(
                session.query(UnopenedHad).filter(
                    UnopenedHad.match_id == odds_info['id'],
                    UnopenedHad.flat_odds == odds_info['d'],
                    UnopenedHad.negative_odds == odds_info['a'],
                    UnopenedHad.winning_odds == odds_info['h'],
                ).exists()
            ).scalar()
            if exists:
                continue

            winning_odds = odds_info['h']
            flat_odds = odds_info['d']
            negative_odds = odds_info['a']
            time = odds_info['time']

            orm_object = UnopenedHad(
                match_id=odds_info['id'],
                winning_odds=winning_odds,
                flat_odds=flat_odds,
                negative_odds=negative_odds,
                time=time
            )
            session.add(orm_object)
            logger.info(
                f"胜负平{orm_object.match_id, orm_object.winning_odds, orm_object.flat_odds, orm_object.negative_odds}数据插入成功！")
        session.commit()
    finally:
        session.close()


def insert_让胜平负(odds_list):
    session = Session()
    try:
        matched_records = session.query(UnopenedHHad).filter(UnopenedHHad.match_id == odds_list[0]['id']).all()
        if len(odds_list) == len(matched_records):
            return
        for odds_info in odds_list:
            exists = session.query(
                session.query(UnopenedHHad).filter(
                    UnopenedHHad.match_id == odds_info['id'],
                    UnopenedHHad.flat_odds == odds_info['d'],
                    UnopenedHHad.negative_odds == odds_info['a'],
                    UnopenedHHad.winning_odds == odds_info['h'],
                ).exists()
            ).scalar()
            if exists:
                continue

            winning_odds = odds_info['h']
            flat_odds = odds_info['d']
            negative_odds = odds_info['a']
            time = odds_info['time']

            orm_object = UnopenedHHad(
                match_id=odds_info['id'],
                winning_odds=winning_odds,
                flat_odds=flat_odds,
                negative_odds=negative_odds,
                time=time
            )
            session.add(orm_object)
        session.commit()
    finally:
        session.close()


class UnopenedTtg(Base):
    __tablename__ = 'unopened_ttg'

    id = Column(Integer, primary_key=True, comment='主键标识')
    match_id = Column(String(32), comment='关联球赛信息id')
    zero = Column(String(12), comment='进0球')
    one = Column(String(12), comment='进1球')
    two = Column(String(12), comment='进2球')
    three = Column(String(12), comment='进3球')
    four = Column(String(12), comment='进4球')
    five = Column(String(12), comment='进5球')
    six = Column(String(12), comment='进6球')
    seven = Column(String(12), comment='进7球')
    time = Column(DateTime, nullable=False, comment='时间')


from sqlalchemy.exc import SQLAlchemyError


def insert_总进球固定奖金(data_array):
    session = Session()
    try:

        for data in data_array:
            data = json.loads(data)
            matched_records = session.query(UnopenedTtg).filter(UnopenedTtg.match_id == data['id']).all()
            if len(data_array) == len(matched_records):
                return
            exists = session.query(
                session.query(UnopenedTtg).filter(
                    UnopenedTtg.match_id == data['id'],
                    UnopenedTtg.zero == data['0'],
                    UnopenedTtg.one == data['1'],
                    UnopenedTtg.two == data['2'],
                    UnopenedTtg.three == data['3'],
                    UnopenedTtg.four == data['4'],
                    UnopenedTtg.five == data['5'],
                    UnopenedTtg.six == data['6'],
                    UnopenedTtg.seven == data['7']
                ).exists()
            ).scalar()
            if exists:
                continue

            record = UnopenedTtg(
                match_id=data.get("id"),
                zero=data["0"],
                one=data["1"],
                two=data["2"],
                three=data["3"],
                four=data["4"],
                five=data["5"],
                six=data["6"],
                seven=data["7"],
                time=data["time"]
            )

            session.add(record)
        session.commit()
        logger.info("所有数据插入成功！")
    except SQLAlchemyError as e:
        session.rollback()
        logger.info(f"数据库错误: {e}")
    finally:
        session.close()


class UnopenedHafu(Base):
    __tablename__ = 'unopened_hafu'
    id = Column(Integer, primary_key=True, comment='主键标识半全场胜平负id')
    match_id = Column(String(32), nullable=False, comment='关联球赛信息id')
    win_win = Column(String(32), nullable=False, comment='胜胜')
    win_flat = Column(String(32), nullable=False, comment='胜平')
    win_draw = Column(String(32), nullable=False, comment='胜负')
    flat_win = Column(String(32), nullable=False, comment='平胜')
    flat_flat = Column(String(32), nullable=False, comment='平平')
    flat_draw = Column(String(32), nullable=False, comment='平负')
    draw_win = Column(String(32), nullable=False, comment='负胜')
    draw_flat = Column(String(32), nullable=False, comment='负平')
    draw_draw = Column(String(32), nullable=False, comment='负负')
    time = Column(DateTime, nullable=False, comment='时间')


def insert_半全场胜平负固定奖金(data_list):
    session = Session()
    try:
        matched_records = session.query(UnopenedHafu).filter(UnopenedHafu.match_id == data_list[0]['id']).all()
        if len(data_list) == len(matched_records):
            return
        for data in data_list:
            exists = session.query(
                session.query(UnopenedHafu).filter(
                    UnopenedHafu.match_id == data['id'],
                    UnopenedHafu.win_win == data['胜胜'],
                    UnopenedHafu.win_flat == data['胜平'],
                    UnopenedHafu.win_draw == data['胜负'],
                    UnopenedHafu.flat_win == data['平胜'],
                    UnopenedHafu.flat_flat == data['平平'],
                    UnopenedHafu.flat_draw == data['平负'],
                    UnopenedHafu.draw_win == data['负胜'],
                    UnopenedHafu.draw_flat == data['负平'],
                    UnopenedHafu.draw_draw == data['负负']
                ).exists()
            ).scalar()
            if exists:
                continue
            logger.info(
                f"半全场{data['id'], data['胜胜'], data['胜平'], data['胜负'], data['平胜'], data['平平'], data['平负'], data['负胜'], data['负平'], data['负负'], data['time']}插入成功")
            record = {
                "match_id": data["id"],
                "win_win": data["胜胜"],
                "win_flat": data["胜平"],
                "win_draw": data["胜负"],
                "flat_win": data["平胜"],
                "flat_flat": data["平平"],
                "flat_draw": data["平负"],
                "draw_win": data["负胜"],
                "draw_flat": data["负平"],
                "draw_draw": data["负负"],
                "time": data["time"]
            }

            session.execute(
                insert(UnopenedHafu).values(record)
            )
        session.commit()
        logger.info("数据插入成功！")
    except SQLAlchemyError as e:
        session.rollback()
        logger.info(f"数据库错误: {e}")
    finally:
        session.close()


class UnopenedCrs(Base):
    __tablename__ = 'unopened_crs'
    id = Column(Integer, primary_key=True)
    match_id = Column(String(32))
    one_zero = Column(String(32))
    two_zero = Column(String(32))
    two_one = Column(String(32))
    three_zero = Column(String(32))
    three_one = Column(String(32))
    three_two = Column(String(32))
    four_zero = Column(String(32))
    four_one = Column(String(32))
    four_two = Column(String(32))
    five_zero = Column(String(32))
    five_one = Column(String(32))
    five_two = Column(String(32))
    win_others = Column(String(32))
    zero_zero = Column(String(32))
    one_one = Column(String(32))
    two_two = Column(String(32))
    three_three = Column(String(32))
    flat_others = Column(String(32))
    zero_one = Column(String(32))
    zero_two = Column(String(32))
    one_two = Column(String(32))
    zero_three = Column(String(32))
    one_three = Column(String(32))
    two_three = Column(String(32))
    zero_four = Column(String(32))
    one_four = Column(String(32))
    two_four = Column(String(32))
    zero_five = Column(String(32))
    one_five = Column(String(32))
    two_five = Column(String(32))
    draw_others = Column(String(32))
    time = Column(DateTime)


def insert_比分固定奖金(matches_info):
    session = Session()
    try:
        matched_records = session.query(UnopenedCrs).filter(UnopenedCrs.match_id == matches_info[0]['id']).all()
        if len(matches_info) == len(matched_records):
            return
        for data in matches_info:
            exists = session.query(
                session.query(UnopenedCrs).filter(
                    UnopenedCrs.match_id == data['id'],
                    UnopenedCrs.one_zero == data['1:0'],
                    UnopenedCrs.two_zero == data['2:0'],
                    UnopenedCrs.two_one == data['2:1'],
                    UnopenedCrs.three_zero == data['3:0'],
                    UnopenedCrs.three_one == data['3:1'],
                    UnopenedCrs.three_two == data['3:2'],
                    UnopenedCrs.four_zero == data['4:0'],
                    UnopenedCrs.four_one == data['4:1'],
                    UnopenedCrs.four_two == data['4:2'],
                    UnopenedCrs.five_zero == data['5:0'],
                    UnopenedCrs.five_one == data['5:1'],
                    UnopenedCrs.five_two == data['5:2'],
                    UnopenedCrs.draw_others == data['负其他'],
                    UnopenedCrs.zero_zero == data['0:0'],
                    UnopenedCrs.one_one == data['1:1'],
                    UnopenedCrs.two_two == data['2:2'],
                    UnopenedCrs.three_three == data['3:3'],
                    UnopenedCrs.flat_others == data['平其他'],
                    UnopenedCrs.zero_one == data['0:1'],
                    UnopenedCrs.zero_two == data['0:2'],
                    UnopenedCrs.one_two == data['1:2'],
                    UnopenedCrs.zero_three == data['0:3'],
                    UnopenedCrs.one_three == data['1:3'],
                    UnopenedCrs.two_three == data['2:3'],
                    UnopenedCrs.zero_four == data['0:4'],
                    UnopenedCrs.one_four == data['1:4'],
                    UnopenedCrs.two_four == data['2:4'],
                    UnopenedCrs.zero_five == data['0:5'],
                    UnopenedCrs.one_five == data['1:5'],
                    UnopenedCrs.two_five == data['2:5'],
                    UnopenedCrs.draw_others == data['负其他']
                ).exists()
            ).scalar()
            if exists:
                continue

            match_id = data['id']
            one_zero = data.get('1:0', None),
            two_zero = data.get('2:0', None),
            two_one = data.get('2:1', None),
            three_zero = data.get('3:0', None),
            three_one = data.get('3:1', None),
            three_two = data.get('3:2', None),
            four_zero = data.get('4:0', None),
            four_one = data.get('4:1', None),
            four_two = data.get('4:2', None),
            five_zero = data.get('5:0', None),
            five_one = data.get('5:1', None),
            five_two = data.get('5:2', None),
            win_others = data.get('胜其他', None),
            zero_zero = data.get('0:0', None),
            one_one = data.get('1:1', None),
            two_two = data.get('2:2', None),
            three_three = data.get('3:3', None),
            flat_others = data.get('平其他', None),
            zero_one = data.get('0:1', None),
            zero_two = data.get('0:2', None),
            one_two = data.get('1:2', None),
            zero_three = data.get('0:3', None),
            one_three = data.get('1:3', None),
            two_three = data.get('2:3', None),
            zero_four = data.get('0:4', None),
            one_four = data.get('1:4', None),
            two_four = data.get('2:4', None),
            zero_five = data.get('0:5', None),
            one_five = data.get('1:5', None),
            two_five = data.get('2:5', None),
            draw_others = data.get('负其他', None),
            time = data.get("time")

            session.add(UnopenedCrs(
                match_id=match_id,
                one_zero=one_zero,
                two_zero=two_zero,
                two_one=two_one,
                three_zero=three_zero,
                three_one=three_one,
                three_two=three_two,
                four_zero=four_zero,
                four_one=four_one,
                four_two=four_two,
                five_zero=five_zero,
                five_one=five_one,
                five_two=five_two,
                win_others=win_others,
                zero_zero=zero_zero,
                one_one=one_one,
                two_two=two_two,
                three_three=three_three,
                flat_others=flat_others,
                zero_one=zero_one,
                zero_two=zero_two,
                one_two=one_two,
                zero_three=zero_three,
                one_three=one_three,
                two_three=two_three,
                zero_four=zero_four,
                one_four=one_four,
                two_four=two_four,
                zero_five=zero_five,
                one_five=one_five,
                two_five=two_five,
                draw_others=draw_others,
                time=time
            ))
        session.commit()
    except (KeyError, ValueError) as e:

        logger.info(f"处理比赛数据时出错: {e}")
    finally:
        session.close()


比分固定奖金最终 = []
半全场胜平负固定奖金最终 = []
总进球固定奖金最终 = []

app = Flask(__name__)


def get_比分固定奖金(entry, id, crs_combination_desc):
    processed_results = {}
    for key, value in entry.items():
        if key.startswith("s-1"):

            if key == "s-1sd":
                processed_results["平其他"] = value
            elif key == "s-1sa":
                processed_results["负其他"] = value
            elif key == "s-1sh":
                processed_results["胜其他"] = value
        elif key.startswith("s") and not key.endswith("f") and value != "0":

            scores = key[1:].split("s")

            score_key = f"{int(scores[0])}:{int(scores[1])}"
            processed_results[score_key] = value
    sorted_results = dict(sorted(processed_results.items(), key=lambda item: (
        0 if item[0] == "胜其他" else
        1 if isinstance(item[0], str) and item[0].count(':') == 1 and int(item[0].split(':')[0]) > int(
            item[0].split(':')[1]) else
        2 if item[0] == "平其他" else
        3
    )))
    sorted_results['id'] = id
    match_datetime_str = f"{entry['updateDate']} {entry['updateTime']}"
    match_datetime = datetime.strptime(match_datetime_str, '%Y-%m-%d %H:%M:%S')
    sorted_results['time'] = match_datetime
    return sorted_results


def process_crs_list(crs_list, id, crs_combination_desc):
    crs_list_sorted = sorted(crs_list, key=lambda x: (x['updateDate'], x['updateTime']))

    for crs_list in crs_list_sorted:
        比分固定奖金最终.append(get_比分固定奖金(crs_list, id, crs_combination_desc))


def process_entry(entry):
    """
    处理单个总进球条目，提取有效数据并返回结果。
    """
    processed_results = {}
    for key, value in entry.items():
        if key.startswith("s") and not key.endswith("f") and value != "0":
            score_key = key[1:]
            processed_results[score_key] = value

    sorted_results = dict(sorted(processed_results.items(), key=lambda item: int(item[0])))

    publication_time = f"{entry['updateDate']} {entry['updateTime']}"
    sorted_results['time'] = publication_time

    return sorted_results


def process_ttg_list(ttg_list, id):
    ttg_list_sorted = sorted(ttg_list, key=lambda x: (x['updateDate'], x['updateTime']))

    for ttg_list in ttg_list_sorted:
        entry_result = process_entry(ttg_list)
        entry_result["id"] = id
        总进球固定奖金最终.append(json.dumps(entry_result, ensure_ascii=False, indent=4))


def process_entry_hafu(entry):
    """
    处理单个总进球条目，提取有效数据并返回结果。
    """
    processed_results = {
        "胜胜": entry["hh"],
        "胜平": entry["hd"],
        "胜负": entry["ha"],
        "平胜": entry["dh"],
        "平平": entry["dd"],
        "平负": entry["da"],
        "负胜": entry["ah"],
        "负平": entry["ad"],
        "负负": entry["aa"]
    }

    publication_time = f"{entry['updateDate']} {entry['updateTime']}"
    processed_results['time'] = publication_time
    processed_results['id'] = entry["id"]
    return processed_results


def process_hafu_list(hafu_list, id):
    hafu_list_sorted = sorted(hafu_list, key=lambda x: (x['updateDate'], x['updateTime']))

    for hafu_list in hafu_list_sorted:
        hafu_list["id"] = id
        半全场胜平负固定奖金最终.append(process_entry_hafu(hafu_list))


headers = {
    'accept': 'application/json, text/javascript, */*; q=0.01',
    'accept-language': 'zh-CN,zh;q=0.9',
    'origin': 'https://www.sporttery.cn',
    'priority': 'u=1, i',
    'referer': 'https://www.sporttery.cn/',
    'sec-ch-ua': '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'empty',
    'sec-fetch-mode': 'cors',
    'sec-fetch-site': 'same-site',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
}


def get_combination_desc(match_result_list, flag):
    try:
        if match_result_list == []:
            return [-1]
        return [result['combinationDesc'] for result in match_result_list if result.get('code', [-1]) == flag]
    except KeyError:
        return [-1, -1]
    except Exception as e:
        print(f"An error occurred: {e}")
        return [-1, -1]


def get_胜平负固定奖金(had_list, id):
    if had_list is None or had_list == {} or had_list == []:
        return {}
    for had in had_list:
        had['id'] = id
        had['time'] = had["updateDate"] + " " + had["updateTime"]
    return had_list


def get_让胜平负固定奖金(had_list, id):
    if had_list is None or had_list == {} or had_list == []:
        return {}
    for had in had_list:
        had['id'] = id
        had['time'] = had["updateDate"] + " " + had["updateTime"]
    return had_list


@app.route('/getInfoByMatchId', methods=['POST'])
def getInfoByMatchId():
    arrs = request.get_json()
    matchId = arrs["matchId"]
    params = {
        'clientCode': '3001',
        'matchId': matchId,
    }
    try:
        response = requests.get(
            'https://webapi.sporttery.cn/gateway/uniform/football/getFixedBonusV1.qry',
            params=params,
            headers=未开奖header,
            proxies=pool.get_fresh_proxy()
        )
        detail_data = response.json()
        match_result_list = detail_data['value'].get('matchResultList', [])
        胜平负固定奖金_list = detail_data['value'].get("oddsHistory").get('hadList', [])
        logger.info(f"胜平负固定奖金_list{胜平负固定奖金_list}")
        让球胜平负固定奖金_list = detail_data['value'].get("oddsHistory").get('hhadList', [])
        比分固定奖金_list = detail_data['value'].get("oddsHistory").get('crsList', [])
        总进球固定奖金_list = detail_data['value'].get("oddsHistory").get('ttgList', [])
        半全场胜平负固定奖金_list = detail_data['value'].get("oddsHistory").get('hafuList', [])
        logger.info(f"总进球固定奖金_list{总进球固定奖金_list}")
        if 胜平负固定奖金_list:
            胜平负 = get_胜平负固定奖金(胜平负固定奖金_list, matchId)
            logger.info(f"胜负平{胜平负}")
            if 胜平负 != {}:
                insert_胜平负(胜平负)
        if 让球胜平负固定奖金_list:
            让胜平负 = get_让胜平负固定奖金(让球胜平负固定奖金_list, matchId)
            if 让胜平负 != {}:
                insert_让胜平负(让胜平负)
        if 比分固定奖金_list:
            process_crs_list(比分固定奖金_list, matchId,
                             get_combination_desc(match_result_list, 'CRS'))
        if 总进球固定奖金_list:
            process_ttg_list(总进球固定奖金_list, matchId)

        if 半全场胜平负固定奖金_list:
            process_hafu_list(半全场胜平负固定奖金_list, matchId)
        insert_总进球固定奖金(总进球固定奖金最终)
        insert_半全场胜平负固定奖金(半全场胜平负固定奖金最终)
        insert_比分固定奖金(比分固定奖金最终)
        logger.info(f"半全场胜平负固定奖金最终{半全场胜平负固定奖金最终}")
        总进球固定奖金最终.clear()
        半全场胜平负固定奖金最终.clear()
        比分固定奖金最终.clear()
    except Exception as e:
        print(f"An error occurred: {e}")
        return jsonify({"message": "An error occurred", "code": 500})
    return jsonify({"message": "Success", "code": 200})


未开奖header = {
    'accept': 'application/json, text/plain, */*',
    'accept-language': 'zh-CN,zh;q=0.9',
    'origin': 'https://www.sporttery.cn',
    'priority': 'u=1, i',
    'referer': 'https://www.sporttery.cn/',
    'sec-ch-ua': '"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'empty',
    'sec-fetch-mode': 'cors',
    'sec-fetch-site': 'same-site',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36',
}
headers = {
    'accept': 'application/json, text/javascript, */*; q=0.01',
    'accept-language': 'zh-CN,zh;q=0.9',
    'origin': 'https://www.sporttery.cn',
    'priority': 'u=1, i',
    'referer': 'https://www.sporttery.cn/',
    'sec-ch-ua': '"Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
    'sec-fetch-dest': 'empty',
    'sec-fetch-mode': 'cors',
    'sec-fetch-site': 'same-site',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36',
}


def fetch_and_process_data():
    from loguru import logger
    logger.info("开始执行更新")
    response = requests.get(
        'https://webapi.sporttery.cn/gateway/uniform/football/getMatchCalculatorV1.qry?poolCode=hhad,had&channel=c',
        headers=headers,
        proxies=pool.get_fresh_proxy()
    )
    try:
        data = response.json()["value"]["matchInfoList"]
    except Exception as e:
        logger.error(f"An error occurred: {e}")
        return {}

    for day in data:
        for match in day["subMatchList"]:
            entry = {
                "比赛id": match["matchId"],
                "比赛编号": match["matchNumStr"],
                "比赛日期": match["matchDate"],
                "联赛简称": match["leagueAbbName"],
                "比赛时间": match["matchTime"],
                "主队简称": match["homeTeamAbbName"],
                "客队简称": match["awayTeamAbbName"]
            }

            insert_unopenedLottery_data([entry])
            params = {
                'clientCode': '3001',
                'matchId': match["matchId"],
            }
            time.sleep(random.uniform(2, 4))
            response = requests.get(
                'https://webapi.sporttery.cn/gateway/uniform/football/getFixedBonusV1.qry',
                params=params,
                headers=未开奖header,
                proxies=pool.get_fresh_proxy()
            )
            detail_data = response.json()
            match_result_list = detail_data['value'].get('matchResultList', [])
            胜平负固定奖金_list = detail_data['value'].get("oddsHistory").get('hadList', [])
            比分固定奖金_list = detail_data['value'].get("oddsHistory").get('crsList', [])
            总进球固定奖金_list = detail_data['value'].get("oddsHistory").get('ttgList', [])
            半全场胜平负固定奖金_list = detail_data['value'].get("oddsHistory").get('hafuList', [])
            让球胜平负固定奖金_list = detail_data['value'].get("oddsHistory").get('hhadList', [])
            if 胜平负固定奖金_list:
                胜平负 = get_胜平负固定奖金(胜平负固定奖金_list, match["matchId"])
                if 胜平负 != {}:
                    insert_胜平负(胜平负)
            if 让球胜平负固定奖金_list:
                让胜平负 = get_让胜平负固定奖金(让球胜平负固定奖金_list, match["matchId"])
                if 让胜平负 != {}:
                    insert_让胜平负(让胜平负)
            if 比分固定奖金_list:
                process_crs_list(比分固定奖金_list, match["matchId"],
                                 get_combination_desc(match_result_list, 'CRS'))
            if 总进球固定奖金_list:
                process_ttg_list(总进球固定奖金_list, match["matchId"])

            if 半全场胜平负固定奖金_list:
                process_hafu_list(半全场胜平负固定奖金_list, match["matchId"])
            insert_总进球固定奖金(总进球固定奖金最终)
            insert_半全场胜平负固定奖金(半全场胜平负固定奖金最终)
            insert_比分固定奖金(比分固定奖金最终)
            总进球固定奖金最终.clear()
            半全场胜平负固定奖金最终.clear()
            比分固定奖金最终.clear()
            胜平负 = ""
    logger.info("执行更新结束")


@app.route('/fetch_data', methods=['GET'])
def fetch_data_route():
    try:
        fetch_and_process_data()
        return jsonify({"status": "success", "message": "Data fetched and processed successfully."}), 200
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500


def run_schedule():
    import schedule
    import time

    schedule.every(60).minutes.do(fetch_and_process_data)
    while True:
        schedule.run_pending()
        time.sleep(1)


if __name__ == '__main__':
    schedule_thread = threading.Thread(target=run_schedule)
    schedule_thread.daemon = True
    schedule_thread.start()

    app.run(host='0.0.0.0', port=15000)
